function AllReady() {
  var mstform = Ext.getCmp("CntM7"); //获取容器
  var tabPanel = Ext.getCmp("tabPanel"); // 获取当前所在 tab 页
  var dgrid = Ext.getCmp("CntD7");
  var dgrid2 = Ext.getCmp("CntPtypeParamList");
  var dstore = dgrid.store;
  var PhidYsfl = mstform.queryById("PhidYsfl");
  var PhidPc = mstform.getItem("PhidPc");
  var user_yztj_no = mstform.getItem("user_yztj_no");
  var user_djfa_no = mstform.getItem("user_djfa_no");
  var PhidSenComp = mstform.getItem("PhidSenComp");
  var Title = mstform.getItem("Title");
  var PhidRecComp = mstform.getItem("PhidRecComp");

  let djLock = 0;
  var user_is_yztj = mstform.getItem("user_is_yztj");
  mstform.getItem("IsPayOverCntSum").setValue("0");
  var toolbar = Ext.getCmp("toolbar");
  toolbar.get("imp").setText("引用采购/备品备件申请");
  toolbar.get("imp_push").hide();
  const storedData = localStorage.getItem("selectedUSourceData");
  console.log(`下推数据`, storedData);
  // 隐藏合同条款删除按钮
  // (['add','edit','view'].includes(otype))&&hidenDeleteBtn()
  // function hidenDeleteBtn(){
  //   window.isDeleteLock = setInterval(()=>{
  //     try{
  //       if(document.querySelector("#cntitemtab-body")){
  //         const element = seachId("cntitemtab-body",[0,0,0,0,0,0])
  //         const Box = Ext.getCmp(element)
  //         Box.queryById("deleterow").hide()
  //         clearInterval(window.isDeleteLock)
  //       }

  //     }catch(err){
  //     }
  //   },1000)
  // }
  // function seachId(id,arr){
  //   let element = document.getElementById(id)
  //   arr.forEach(item=>{
  //     element = document.getElementById(element.children[item].id)
  //   })
  //   return element.id
  // }
  ////////////////////////////////////////////////////////////-- toolbar --////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////-- toolbar --////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////-- toolbar --////////////////////////////////////////////////////////////
  // 新增“推送上上签”按钮
  var pushButton = toolbar.add({
    xtype: "button",
    text: "推送上上签",
    id: "pushBtn",
    iconCls: "icon-New",
    handler: function () {
      // 按钮点击后执行的逻辑，发送 AJAX 请求
      var phid = mstform.getItem("Phid").getValue(); // 假设 phid 存在于表单中
      var asrTable = mstform.getItem("asrTable").getValue(); // 假设 asrTable 存在于表单中

      // 拼接查询参数
      var url = "https://sd.hisense.com/sd/sapwSigned/Signed/push/uploadContract" + "?phid=" + phid + "&asrTable=" + asrTable;

      // 使用 GET 请求
      Ext.Ajax.request({
        url: url,
        method: "POST",
        success: function (response) {
          var res = Ext.decode(response.responseText);
          if (res.success) {
            Ext.Msg.alert("提示");
          } else {
            Ext.Msg.alert("错误", "推送失败");
          }
        },
        failure: function () {
          Ext.Msg.alert("错误", "请求失败，请稍后再试");
        },
      });
    },
  });
  if (otype == "add") {
    hidenDeleteBtn();
    viewBtn("CntM7");

  }
  mstform.on('dataready', function () {
      viewBtn("CntM7");
});

  function hidenDeleteBtn() {
    window.isDeleteLock = setInterval(() => {
      try {
        if (document.querySelector("#cntitemtab-body")) {
          const element = seachId("cntitemtab-body", [0, 0, 0, 0, 0, 0]);
          const Box = Ext.getCmp(element);
          var dstore = Box.store;
          dstore.getAt(0).set("user_fktj", "1");
          dstore.getAt(1).set("user_fktj", "2");
          dstore.getAt(2).set("user_fktj", "3");
          dstore.getAt(3).set("user_fktj", "5");
          dstore.getAt(4).set("user_fktj", "6");
          dstore.getAt(5).set("user_fktj", "7");
          // Box.queryById("deleterow").hide()
          clearInterval(window.isDeleteLock);
        }
      } catch (err) {}
    }, 1000);
  }
  function seachId(id, arr) {
    let element = document.getElementById(id);
    arr.forEach((item) => {
      element = document.getElementById(element.children[item].id);
    });
    return element.id;
  }

  // const extGrid = Ext.getCmp(targetGrid.id);
  // console.log(extGrid);

  // >>>>>>>>>>>>>>>>>>查询合同状态签署完成后自动下载合同 START <<<<<<<<<<<<<<<<<<<<<<<<<<
  /**
   * @param form 主表容器ID
   * 当前默认存储上上签合同id字段为 user_contractid ,如果不一样请传参key
   * @param key 上上签合同id字段（默认可不填）
   */
  function viewBtn(form, key) {
    var mstform = Ext.getCmp(form);
    var toolbar = Ext.getCmp("toolbar");
    const is = mstform.getValues().user_isdownload
    console.log(`debug`,mstform.getValues());
    if(is == '1'){
        return
    }
    toolbar.add({
      xtype: "button",
      text: "查询合同状态",
      id: "viewBtn",
      iconCls: "icon-New",
      handler: function () {
        // 按钮点击后执行的逻辑，发送 AJAX 请求
        var phid = mstform.getItem("PhId").getValue(); // 假设 phid 存在于表单中
        //   var asrTable = mstform.getItem("asrTable").getValue(); // 假设 asrTable 存在于表单中

        // 拼接查询参数
        var url = "https://sd.hisense.com/sd/sapwSigned/Signed/push/checkContractStatus";
        var user_contractid = mstform.queryById(key ? key : "user_contractid")?.getValue();
        console.log(user_contractid, phid);
        if (!user_contractid || !phid) {
          Ext.Msg.alert("错误", "当前合同未推送至上上签 或 单据为审核！");
          return;
        }
        // 使用 GET 请求
        Ext.Ajax.request({
          url: url,
          method: "POST",
          headers: { "Content-Type": "application/json" },
          jsonData: { contractId: user_contractid ,
                    tabname: "pcm3_cnt_m"
                    },
          success: function (response) {
            var res = Ext.decode(response.responseText);
            if (res.IsOk) {
              Ext.Msg.alert("提示", res.data);
            } else {
              Ext.Msg.alert("错误", res.data);
            }
          },
          failure: function () {
            Ext.Msg.alert("错误", "请求失败，请稍后再试");
          },
        });
      },
    });
  }
  function beforeSaveEdit() {
    var mstform = Ext.getCmp("KC_OUTBZTL_Head");
    var dgrid2 = Ext.getCmp("CntPtypeParamList");
    var dstore = dgrid2.store;

    for (let i = 0; i < dstore.getCount(); i++) {
      // var DbTaxprc = Number(dstore.getAt(i).get('DbTaxprc'));//调拨含税单价
      console.log(dstore.getAt(i));

      // var DbTaxprc = Number(dstore.getAt(i).get('DbTaxprc'));
      // DbTaxprc = Math.trunc(DbTaxprc * 1000000) / 1000000;
      // var Taxprc = Number(dstore.getAt(i).get('Taxprc'));//含税成本单价
      // console.log(DbTaxprc, Taxprc);

      // if (DbTaxprc > Taxprc) {//调拨含税单价大于含税成本单价时，无法保存

      //     Ext.Msg.alert('提示', '第' + [i + 1] + '行明细折价大于成本价，无法保存');
      //     Ext.getCmp('toolbar').get("save").enable();
      //     return false;

      // }
    }
    return true;
  }
  // >>>>>>>>>>>>>>>>>>查询合同状态签署完成后自动下载合同 End <<<<<<<<<<<<<<<<<<<<<<<<<<
  if (otype == "add" || otype == "edit") {
    setTimeout(() => {
      if (mstform.getItem("CntType").getValue() == 8570000000000008) {
        mstform.getItem("user_sjbm").userSetMustInput(false);
      }
    }, 500);
  }
  if (mstform.getItem("CntType").getValue() == 8570000000000008) {
    mstform.getItem("user_sjbm").userSetMustInput(false);
  }
  if (otype == "add") {
    if (mstform.getItem("user_lj_amt").getValue()) {
    } else {
      mstform.getItem("user_lj_amt").setValue(0);
    }
    if (mstform.getItem("user_unpaid_amt").getValue()) {
    } else {
      mstform.getItem("user_unpaid_amt").setValue(0);
    }
    if (mstform.getItem("user_payable_amt").getValue()) {
    } else {
      mstform.getItem("user_payable_amt").setValue(0);
    }
    addContractTerms();
  }
  if (otype == "add") {
    if (mstform.getItem("PhidPc").getValue()) {
      getPtInfoByPhid();
    }
    setTimeout(() => {
      console.log($appinfo.orgID);
      mstform.getItem("PhidOcode").setValue(Number($appinfo.orgID));
      BatchBindCombox(mstform.getItem("PhidOcode"));
      console.log(mstform.getItem("PhidOcode").getValue());
    }, 500);
    PhidYsfl.setValue("14");
    BatchBindCombox([PhidYsfl]);
  }

  user_is_yztj.addListener("change", function (args) {
    console.log("args.value??XX", args.value);
  });

  mstform.getItem("CntType").addListener("change", function (args) {
    if (mstform.getItem("CntType").getValue() == 8570000000000008) {
      mstform.getItem("user_sjbm").userSetMustInput(false);
    }
  });
  mstform.getItem("PhidPc").addListener("change", function (args) {
    getPtInfoByPhid();
    getSuppyPhone();
  });
  mstform.getItem("PhidRecComp").addListener("change", function (args) {
    const phid = mstform.getItem("PhidRecComp").getValue();
    if (phid) {
      execServer("searchWldw", { phid }, (res) => {
        if (res.count == 0 || !res.count) {
          return;
        } else {
          const data = JSON.parse(res.data)[0].extendObjects;
          console.log(data);
          mstform.getItem("user_jfzcdz").setValue(data.user_zc_address); //注册地址
          mstform.getItem("user_customer_address").setValue(data.officeaddr); //联系地址
          mstform.getItem("user_customer_account").setValue(data.user_yhzh); //开户账号
          mstform.getItem("user_jfsh").setValue(data.user_wldwsh);
          mstform.getItem("user_jfyzbm").setValue(data.postcode); //邮编
          mstform.getItem("user_customer_bank").setValue(data.user_wldwkhyhxx); //开户银行
          BatchBindCombox([mstform.getItem("user_customer_bank")]);
          // mstform.getItem('user_customer_address').setValue(data.postcode)
        }
      });
    }
    getSuppyPhone();
  });
  allSameValue();
  mstform.getItem("PhidSenComp").addListener("change", function (args) {
    dstore.each(function (record) {
      console.log(mstform.getItem("PhidSenComp").getValue(), "PhidSenComp");
      console.log(mstform.getItem("user_sjbm").getValue(), "user_sjbm");

      async function asfun() {
        try {
          const res1 = await new Promise((resolve, reject) => {
            execServer("autoSelectType", { id: record.data.PhidItemId }, function (res) {
              resolve(res);
            });
          });
          const resWzxlData = JSON.parse(res1.data)[0].extendObjects;
          const res2 = await new Promise((resolve, reject) => {
            execServer("getAutoType", { phid: resWzxlData.phid_resbs }, function (res) {
              resolve(res);
            });
          });
          const datas = JSON.parse(res2.data)[0].extendObjects;
          record.set("user_item_xl_name", datas.name);
          record.set("user_item_xl", resWzxlData.phid_resbs);
          record.set("user_item_zl_name", datas.fname);
          record.set("user_item_zl", datas.f_phid);
          record.set("user_item_dl_name", datas.gname);
          record.set("user_item_dl", datas.g_phid);
          let phid1 = record.data.PhidItemdata;
          if (record.data.PhidItemdata) {
            execServer("getDHZQItemDataInfo", { phid: `'${phid1}'` }, function (res) {
              try {
                const datas = JSON.parse(res.data);
                let DHZQ1 = datas[0].extendObjects.user_dhzq;
                const newDate = addDaysToDate(mstform.getItem("BillDt").value, DHZQ1);
                record.set("user_ckdh_dt", newDate);
              } catch (error) {
                Ext.Msg.alert("服务器错误，请联系管理员");
              }
            });
          } else if (record.data.PhidItemId) {
            execServer("getDHZQItemDataInfo", { phid: record.data.PhidItemId }, function (res) {
              try {
                const datas = JSON.parse(res.data);
                let DHZQ1 = datas[0].extendObjects.user_dhzq;
                const newDate = addDaysToDate(mstform.getItem("BillDt").value, DHZQ1);
                record.set("user_ckdh_dt", newDate);
              } catch (error) {
                Ext.Msg.alert("服务器错误，请联系管理员");
              }
            });
          }
        } catch (error) {
          console.error(error);
        }
      }
      if (!record.data.PhidItemId) return;
      record.set("ItemName", record.data.PhidItemId_EXName);
      record.set("ItemNo", record.data.ItemDataNo);
      if (mstform.getItem("PhidSenComp").getValue() && mstform.getItem("user_sjbm").getValue() && record.data.PhidItemId) {
        getBeforePrice(record);
      }
      asfun();
      dgrid.getView().refresh();
    });
  });
  user_yztj_no.on("beforetriggerclick", function (eOp, ignoreBeforeEvent) {
    if (Ext.isEmpty(PhidPc.getValue())) {
      Ext.Msg.alert("提示", "请先选择工程项目！"); //未选择提示：请先选择项目！
      return false;
    }
    user_yztj_no.setOutFilter({
      u_sj_no: mstform.getItem("user_sjbm").getValue(),
      u_sj_name: mstform.getItem("user_sjmc").getValue(),
    });
  });
  user_djfa_no.on("beforetriggerclick", function (eOp, ignoreBeforeEvent) {
    if (Ext.isEmpty(PhidPc.getValue())) {
      Ext.Msg.alert("提示", "请先选择工程项目！"); //未选择提示：请先选择项目！
      return false;
    }

    user_djfa_no.setOutFilter({
      u_sjh: mstform.getItem("user_sjbm").getValue(),
    });
  });
  user_djfa_no.addListener("helpselected", function (args) {
    mstform.getItem("user_djfs").setValue(args.data?.u_zbfs); //付款方式
    BatchBindCombox([mstform.getItem("user_djfs")]);
    execServer(
      "getfkfs",
      {
        no: `'${args?.data?.bill_no}'`,
      },
      function (res) {
        try {
          const datas = JSON.parse(res.data)[0].extendObjects;
          mstform.getItem("user_fkfs").setValue(datas?.user_fkfs); //付款方式
        } catch (error) {
          mstform.getItem("user_fkfs").setValue(""); //付款方式
        }
      }
    );
  });
  // 监听区域中心
  mstform.getItem("user_regional_center").addListener("change", function (args) {
    mstform.getItem("user_regional_center").setValue(args.value); //区域中心
    BatchBindCombox([mstform.getItem("user_regional_center")]);
  });
  // 监听采购组织
  mstform.getItem("user_pur_org").addListener("change", function (args) {
    BatchBindCombox([mstform.getItem("user_pur_org")]);
  });
  // 监听采购合同税率
  // mstform.getItem("user_taxrate").addListener("change", function (args) {
  //   console.log(args);
  //   // mstform.getValues().user_taxrate;
  //   console.log(mstform.getValues().user_taxrate);
  //   dstore.each(function (item) {
  //     item.set("TaxRate", mstform.getValues().user_taxrate);
  //   });
  // });
  // 监听业主推荐单号
  mstform.getItem("user_yztj_no").addListener("change", function (args) {
    if (args.value == 1) {
      execServer(
        "GETyztj",
        {
          pc: mstform.getItem("pc").getValue(),
        },
        function (res) {
          const datas = JSON.parse(res.data)[0].extendObjects;
        }
      );
    }
  });
  mstform.getItem("ChineseAmtVatFc").addListener("change", function (args) {
    let amt = mstform.getItem("ChineseAmtVatFc").getValue();
    mstform.getItem("user_dxhejehj").setValue(amt);
  });
  setTimeout(() => {
    console.log(mstform.getItem("ChineseAmtVatFc").getValue(), "获取大写的金额");
    let amt = mstform.getItem("ChineseAmtVatFc").getValue();
    mstform.getItem("user_dxhejehj").setValue(amt);
  }, 500);
  mstform.getItem("PhidSenComp").addListener("change", function (args) {
    if (!mstform.getItem("PhidSenComp").getValue()) return;
    console.log(mstform.getItem("PhidSenComp").getValue());

    // execServer(
    //   "getEnterpriseInfoByPhid",
    //   {
    //     phid: mstform.getItem("PhidSenComp").getValue(),
    //   },
    //   function (res) {
    //     const datas = JSON.parse(res.data)[0].extendObjects; // 植物user_duties  mainrole
    //     mstform.getItem("user_khbank").setValue(datas.taxbankname); //开户银行
    //     mstform.getItem("user_supply_address").setValue(datas.taxaddress); //注册地址
    //     mstform.getItem("user_bankno").setValue(datas.bankno); //开户银行行号
    //     // mstform.getItem("user_sh").setValue(datas.); //税号
    //     // mstform.getItem("user_yzbm").setValue(datas.); //税号
    //     mstform.getItem("user_tyshxydm").setValue(datas.unisocialcredit);
    //     mstform.getItem("user_khbank").setValue(datas.taxbankname);
    //     mstform.getItem("user_bankno").setValue(datas.taxaccountno);
    //     console.log("业主推荐", datas);
    //   }
    // );
    execServer(
      "searchGys",
      {
        phid: `'${mstform.getItem("PhidSenComp").getValue()}'`,
      },
      function (res) {
        const datas = JSON.parse(res.data)[0].extendObjects; // 植物user_duties  mainrole
        console.log(datas);

        mstform.getItem("user_supply_address").setValue(datas.user_zc_address); //注册地址
        mstform.getItem("user_ghf_contacts").setValue(datas.cname); //联系人
        mstform.getItem("user_gflxdz").setValue(datas.officeaddr); //联系地址
        mstform.getItem("user_yzbm").setValue(datas.user_yzbm); //邮政编码
        mstform.getItem("user_tyshxydm").setValue(datas.unisocialcredit); //
        mstform.getItem("user_bankno").setValue(datas.user_khhhh); //开户银行号
        mstform.getItem("user_bank_account").setValue(datas.accountno); //开户银行帐号
        mstform.getItem("user_sh").setValue(datas.taxno); //税号
        mstform.getItem("user_mailbox").setValue(datas.email); //邮箱
        mstform.getItem("user_gfkhyh").setValue(datas.phid_bank); //开户银行
        BatchBindCombox([mstform.getItem("user_gfkhyh")]);
      }
    );
    execServer(
      "GETlinkman",
      {
        ent: mstform.getItem("PhidSenComp").getValue(),
      },
      function (res) {
        if (res.count == 0) return;
        const datas = JSON.parse(res.data)[0].extendObjects;
        // 植物user_duties  mainrole
        mstform.getItem("user_duties").setValue(datas.mainrole); //职务
        mstform.getItem("user_contact_information").setValue(datas.handset); //联系方式
        mstform.getItem("user_payee").setValue(datas.phid); //收款方
        BatchBindCombox([mstform.getItem("user_payee")]);
        mstform.getItem("user_bank_account").setValue(datas.accountno); //银行卡
        mstform.getItem("user_ghf_contacts").setValue(datas.cname); //供方联系人
        mstform.getItem("user_mailbox").setValue(datas.email); //供方联系人
        // mstform.getItem("user_tyshxydm").setValue(datas.unisocialcredit);

        console.log("业主推荐", datas);
      }
    );
  });

  //申请部门//申请人111//采购组织
  if (otype == "add" || otype == "copy" || otype == "edit") {
    execServer("GETuserdept", { phid: $appinfo.userID }, function (res) {
      const datas = JSON.parse(res.data)[0].extendObjects;
      if (res.count > 0) {
        mstform.getItem("user_apply_dept").setValue(datas.dept_id); //申请部门
        mstform.getItem("PhidCm").setValue(datas.hrid); //申请人111
        BatchBindCombox([mstform.getItem("user_apply_dept")]);
        BatchBindCombox([mstform.getItem("PhidCm")]);
      }
    });
    if ($appinfo.ocode) {
      execServer("GETORG", { code: $appinfo.ocode }, function (res) {
        const datas = JSON.parse(res.data)[0].extendObjects;
        if (res.count > 0) {
          mstform.getItem("user_pur_org").setValue("" + datas.phid); //采购组织
        }
      });
    }
  }
  setTimeout(() => {
    try {
      BatchBindCombox([mstform.getItem("user_regional_center")]);
      BatchBindCombox([mstform.getItem("user_product_line")]);
      BatchBindCombox([mstform.getItem("user_pur_req_no")]);
    } catch (e) {}
  }, 500);
  mstform.on("dataready", async function () {
    setTimeout(() => {
      BatchBindCombox([mstform.getItem("user_product_line")]);
      BatchBindCombox([mstform.getItem("user_pur_req_no")]);
    }, 300);
  });

  // 获取甲方单位信息
  function getSuppyPhone() {
    const phid = mstform.getItem("PhidRecComp").getValue();
    if (phid) {
      mstform.queryById("user_jfdw_tel").setValue("");
      execServer("getSuppyPhone", { phid }, (res) => {
        if (res.count == 0 || !res.count) {
          window._saveLock = true;
          return;
        } else {
          const data = JSON.parse(res.data)[0].extendObjects;
          console.log(data);

          const phone = JSON.parse(res.data)[0].extendObjects.phone;
          mstform.queryById("user_jfdw_tel").setValue(phone);
        }
      });
    }
  }

  /**
   *@function:带出项目信息
   */
  function getPtInfoByPhid() {
    console.log("带出项目信息", mstform.getItem("PhidPc").getValue());
    if (mstform.getItem("PhidPc").getValue()) {
      execServer("getPtInfoByPhid", { phid: mstform.getItem("PhidPc").getValue() }, function (res) {
        const datas = JSON.parse(res.data)[0].extendObjects;
        console.log(datas);

        mstform.getItem("user_regional_center").setValue(datas.regional_center_phid); //区域中心
        mstform.getItem("PhidPm").setValue(datas.project_manager_phid); //项目经理
        mstform.getItem("SenEmp").setValue(datas.user_sqgw_phid); //部门商务
        mstform.getItem("user_sjbm").setValue(datas.user_sjbm); //部门商务
        mstform.getItem("user_product_line").setValue(datas.midwife_phid); //事业线
        mstform.getItem("user_division").setValue(datas.division_phid); //事业线
        mstform.getItem("PhidOcode").setValue(datas.cwhszz); //事业线
        BatchBindCombox([mstform.getItem("PhidOcode")]);
        BatchBindCombox([mstform.getItem("user_division")]);
        BatchBindCombox([mstform.getItem("user_product_line")]);
        BatchBindCombox([mstform.getItem("user_regional_center")]);
        BatchBindCombox([mstform.getItem("user_project_manager")]);
        BatchBindCombox([mstform.getItem("SenEmp")]);
        BatchBindCombox([mstform.getItem("PhidPm")]);
      });

      execServer("projectSjbm", { phid: mstform.getItem("PhidPc").getValue() }, async function (res) {
        const datas = JSON.parse(res.data)[0].extendObjects;
        Title.setValue(`${datas.user_sjmc}-采购合同`);
        mstform.getItem("user_sjbm").setValue(datas.user_sjbm); //
        mstform.getItem("user_sjmc").setValue(datas.user_sjmc); //
        BatchBindCombox([mstform.getItem("user_sjbm")]);
        BatchBindCombox([mstform.getItem("user_sjmc")]);

        await execServer("isYzPush", { sjno: "'" + datas.user_sjbm + "'" }, function (res1) {
          if (res1.data.length > 0) {
            mstform.getItem("user_is_yztj").setValue("1");
          } else {
            mstform.getItem("user_is_yztj").setValue("0");
          }
          BatchBindCombox([mstform.getItem("user_is_yztj")]);
        });
      });
      execServer("getXmname", { phid: mstform.getItem("PhidPc").getValue() }, async function (res) {
        const datas = JSON.parse(res.data)[0].extendObjects;
        Title.setValue(`${datas.bill_name}-采购合同`);
      });
      dstore.each(function (record) {
        async function asfun() {
          try {
            const res1 = await new Promise((resolve, reject) => {
              execServer("autoSelectType", { id: record.data.PhidItemId }, function (res) {
                resolve(res);
              });
            });
            const resWzxlData = JSON.parse(res1.data)[0].extendObjects;
            const res2 = await new Promise((resolve, reject) => {
              execServer("getAutoType", { phid: resWzxlData.phid_resbs }, function (res) {
                resolve(res);
              });
            });
            const datas = JSON.parse(res2.data)[0].extendObjects;

            record.set("user_item_xl_name", datas.name);
            record.set("user_item_xl", resWzxlData.phid_resbs);
            record.set("user_item_zl_name", datas.fname);
            record.set("user_item_zl", datas.f_phid);
            record.set("user_item_dl_name", datas.gname);
            record.set("user_item_dl", datas.g_phid);
            if (!record.data.PhidItemId) return; //判断是否为空
            // execServer("GETitemzq", { phid: record.data.PhidItemId }, function (res) {
            //   try {
            //     const datas = JSON.parse(res.data);
            //     let DHZQ1 = datas[0].extendObjects.user_dhzq;
            //     const newDate = addDaysToDate(mstform.getItem("BillDt").value, DHZQ);
            //     record.set("user_delivery_cycle", DHZQ);
            //     record.set("user_exp_arrival_date", newDate);
            //   } catch (error) {
            //     Ext.Msg.alert("服务器错误，请联系管理员");
            //   }
            // });
          } catch (error) {
            console.error(error);
          }
        }
        if (!record.data.PhidItemId) return;
        record.set("ItemName", record.data.PhidItemId_EXName);
        record.set("ItemNo", record.data.ItemDataNo);
        if (mstform.getItem("PhidSenComp").getValue() && mstform.getItem("user_sjbm").getValue() && record.data.PhidItemId) {
          getBeforePrice(record);
        }

        asfun();
      });
    }
  }
  dgrid.addListener("edit", function (editor, e) {
    // var record = e.record;
    // if (e.originalValue == e.value) {
    //   return;
    // }
    // record.set("user_yhsyl", record.get("Qty"));
    // var data = dgrid.getSelectionModel().getSelection();
    // var AMT = data[0].data.Qty * data[0].data.PrcFc;
    // var AmtVat = data[0].data.Qty * data[0].data.PrcVatFc;
    // var jbe = (data[0].data.user_pshsdj - data[0].data.PrcVatFc)*data[0].data.Qty;
    // record.set("user_jcb_amt", jbe);
    // record.set("AmtFc", AMT);
    // record.set("AmtVatFc", AmtVat);
    // if (data[0].data.PrcFc > data[0].data.user_review_prc) {
    //   record.set("PrcFc", 0);
    //   Ext.Msg.alert("提示", "合同未税单价不能大于评审未税单价！");
    // }else
    // if (data[0].data.Qty > data[0].data.user_sbqd_qty) {
    //   record.set("Qty", 0);
    //   Ext.Msg.alert("提示", "采购数量不能大于设备清单总量！");
    // }
    // else {
    // }
    SetTotal();
  });

  function tarChange(params) {
    Ext.each(dstore.getRange(), function (records, index) {
      const row = records.store.data.items;
      Ext.each(row, function (r) {
        const current = r.data.user_review_prc; // 评审价格
        const nowValue = r.data.PrcFc; // 当前价格

        // 添加核心判断逻辑
        if (nowValue > current) {
          // 弹出提示（ExtJS标准方式）
          Ext.Msg.alert("警告", "当前价格超过评审价格，自动重置为0");

          // 修改价格字段（通过set方法保证数据更新）
          r.set("PrcFc", 0);
        }

        console.log(current, nowValue);
      });
    });
  }
  dgrid.addListener("edit", function (editor, e) {
    var record = e.record;
    mapRate();
    mapqty();
  });
  function mapRate(params) {
    var taxRates = []; // 存储所有税率值的数组
    var allSameValue; // 存储统一税率值（如果存在）
    Ext.each(dstore.getRange(), function (records, index) {
      const row = records.store.data.items;
      Ext.each(row, function (r) {
        const currentTaxRate = r.data.OriTaxRate; // 获取当前行的税率
        taxRates.push(currentTaxRate); // 存入数组
      });
      const isAllSame = taxRates.length > 0 && taxRates.every((rate) => rate === taxRates[0]);

      // 如果全部相同，取出统一值
      if (isAllSame) {
        allSameValue = taxRates[0]; // 保存相同的税率值
        mstform.getItem("user_taxrate").setValue(allSameValue);
        console.log("统一税率值:", allSameValue);
        // 在此执行你的统一逻辑（例如更新全局变量或界面）
      } else {
        mstform.getItem("user_taxrate").setValue("");
        console.log("税率不一致");
        // 在此执行不一致逻辑
      }
    });
  }
  function mapqty(params) {
    Ext.each(dstore.getRange(), function (records, index) {
      const row = records.store.data.items;
      Ext.each(row, function (r) {
        const user_sq_qty = r.data.user_sq_qty; // 申请数量
        const Qty = r.data.Qty; // 采购数量
        // 添加核心判断逻辑
        if (Qty > user_sq_qty) {
          // 弹出提示（ExtJS标准方式）
          Ext.Msg.alert("警告", "采购数量超过申请数量，自动重置为0");
          r.set("Qty", 0);
          var AMT = Qty * r.data.PrcFc;
          var AMTvat = Qty * r.data.PrcVatFc;
          r.set("AmtFc", 0);
          r.set("AmtVatFc", 0);
          // 修改价格字段（通过set方法保证数据更新）
        }
      });
    });
  }
  function allSameValue(params) {
    var taxRates = []; // 存储所有税率值的数组
    var allSameValue; // 存储统一税率值（如果存在）
    Ext.each(dstore.getRange(), function (records, index) {
      const row = records.store.data.items;
      Ext.each(row, function (r) {
        const currentTaxRate = r.data.OriTaxRate; // 获取当前行的税率
        taxRates.push(currentTaxRate); // 存入数组
      });
      const isAllSame = taxRates.length > 0 && taxRates.every((rate) => rate === taxRates[0]);

      // 如果全部相同，取出统一值
      if (isAllSame) {
        allSameValue = taxRates[0]; // 保存相同的税率值
        mstform.getItem("user_taxrate").setValue(allSameValue);
        console.log("统一税率值:", allSameValue);
        // 在此执行你的统一逻辑（例如更新全局变量或界面）
      } else {
        mstform.getItem("user_taxrate").setValue("");
        console.log("税率不一致");
        // 在此执行不一致逻辑
      }
    });
  }

  if (storedData) {
    const parsedData = JSON.parse(storedData);
    // setTimeout(() => {

    //   PhidPc.userSetReadOnly(false);
    // }, 500);
    // 获取行数
    const gridCount = parsedData.length;

    let gridArr = []; // 初始化数组

    // 将 execServer 封装为 Promise
    function fetchData(item) {
      return new Promise((resolve, reject) => {
        execServer("getDjxqcByPhid", { phid: item.u_source_id, resource_table: `'${item.u_source_table}'` }, function (res) {
          try {
            console.log("进入功能扩展getDjxqcByPhid1");
            console.log(item.u_source_id, item.u_source_table);
            console.log(res);

            if (res.count > 0) {
              const data = JSON.parse(res.data)[0].extendObjects;
              console.log("debug778", data);
              execServer("getcnt_jf", { sbqd_no: data.user_sbqd_no, phid_pc: data.phid_pc }, function (res) {
                if (res.count > 0) {
                  const dwdatas = JSON.parse(res.data)[0].extendObjects;
                  console.log(dwdatas, "获取甲方单位");
                  mstform.getItem("PhidRecComp").setValue(dwdatas.supply);
                  BatchBindCombox([mstform.getItem("PhidRecComp")]);
                }
              });
              let PhidItemdata1 = data.item_phid;
              let phidpc = data.phid_pc;
              PhidPc.setValue(data?.phid_pc);
              BatchBindCombox([PhidPc]);
              PhidSenComp.setValue(data?.supply_id);
              BatchBindCombox([PhidSenComp]);
              if (data.u_qty > data.sbqd_qty) {
                Ext.Msg.alert("采购数量大于设备清单总量");
              }

              let gridObj = {
                OperFlg: "cnt",
                PhidSourceId: data.source_id,
                user_source_table: data.source_table,
                user_pp: "",
                // PhidItemId: data.item_phid,
                PhidItemId_EXName: data.item_name,
                PhidItemdata: data.item_phid,
                ItemDataNo: data.u_wl_no,
                user_u_equipment_list_no: data.user_sbqd_no,
                user_sb_list_name: data.user_sbqd_name,
                ItemNo: data.item_no,
                ItemName: data.item_name,
                user_sbqd_qty: data.sbqd_qty,
                Unit: data.unit_phid,
                Unit_EXName: data.unit_name,
                Spec: data.spec,
                PhidResBs_EXCode: data.xl_no,
                PhidResBs_EXName: data.resbs_name,
                PrcVatFc: data.u_zb_prc_vat,
                PrcFc: data.u_zb_prc,
                user_review_prc: data.ncg_prc,
                user_pshsdj: data.ncg_prc_vat,
                user_sq_qty: data.u_qty,
                u_ncg_qty: data.u_qty,
                u_yztj_prc: data.u_vat_prc,
                TaxRate: data.u_zb_rate,
                PhidPc: data.phid_pc,
                PhidPc_EXName: data.u_sj_name,
                Qty: data.u_qty,
                prc: data.u_vat_prc,
                // PhidResBs_Code: data.resbs_phid,
                PhidResBs: data.resbs_phid,
                PhidResBs_EXName: data.resbs_name,
                user_djbm: data.bill_no,
                user_djly: data.djly,
                AmtFc: data.u_zb_prc * data.u_qty,
                AmtVatFc: data.u_zb_prc_vat * data.u_qty,
                TaxAmt: data.u_zb_prc * data.u_qty * data.u_zb_rate,
                user_jcb_amt: (data.ncg_prc_vat - data.u_zb_prc_vat) * data.u_qty,
                // user_wlphid: data.item_phid,
              };
              if (data.djly == "采购申请") {
                mstform.getItem("CntType").setValue("8570000000000006");
                BatchBindCombox([mstform.getItem("CntType")]);
                execServer(
                  "searchCgsqPp",
                  {
                    PhidItemdata: `'${PhidItemdata1}' and phid_pc = '${phidpc}'`,
                  },
                  async function (res) {
                    console.log(res, "111111");

                    if (res.count == 0) {
                      gridObj.user_pp = "";
                      return;
                    }
                    const datas = JSON.parse(res.data)[0].extendObjects;
                    const u_brand = datas.user_brand;

                    // 异步更新 gridObj
                    console.log(`debug获取采购申请`, datas.user_pp, datas.user_technical_parameter);
                    gridObj.user_pp = u_brand;
                    gridObj.user_pp = datas.user_pp;
                    gridObj.user_jscs = datas.user_technical_parameter;
                    console.log("更新后的 gridObj:", gridObj);
                  }
                );
              } else if (data.djly === "采购申请") {
                execServer(
                  "searchCgsqPp",
                  {
                    PhidItemdata: `'${PhidItemdata1}' and phid_pc = '${phidpc}'`,
                  },
                  async function (res) {
                    console.log(res, "22222");
                    if (res.count == 0) {
                      gridObj.user_pp = "";
                      return;
                    }
                    const datas = JSON.parse(res.data)[0].extendObjects;
                    const u_brand = datas.user_brand;

                    // 异步更新 gridObj
                    gridObj.user_pp = u_brand;
                    console.log("更新后的 gridObj:", gridObj);
                  }
                );
              } else if (data.djly === "采购申请") {
                	mstform.getItem("CntType").setValue("8570000000000006");
              }
              resolve(gridObj);
              // mapRate()
              // SetTotal();
              // dgrid.getView().refresh();
            } else {
              console.log("功能扩展暂无数据");
              resolve(null);
            }
          } catch (error) {
            console.error("功能扩展报错:", error);
            reject(error);
          }
        });
      });
    }

    // 执行所有异步请求
    async function fetchAllData() {
      try {
        let results = await Promise.all(parsedData.map(fetchData));

        gridArr = results.filter(Boolean); // 过滤掉 null
        // 调用新增表体行数据的函数
        if (gridArr.length > 0) {
          // dstore.insert(dstore.getCount(), gridArr);
          dstore.add(gridArr);
        } else {
          console.warn("未能添加任何数据");
        }
        // 清除 LocalStorage 数据
        localStorage.removeItem("selectedUSourceData");
        console.log("LocalStorage 已清除");
      } catch (error) {
        console.error("获取数据出错:", error);
      }
    }
    fetchAllData(); // 调用异步方法
  } else {
    console.log("LocalStorage 中没有数据");
  }
  //监听 物料名称
  dgrid
    .getColumn("PhidItemId_EXName")
    .getEditor()
    .addListener("helpselected", function (record) {
      var data = dgrid.getSelectionModel().getSelection();
      data[0].set("ItemName", data[0].data.PhidItemId_EXName);
      data[0].set("ItemNo", data[0].data.ItemDataNo);
      execServer("autoSelectType", { id: record.data.PhId }, function (res) {
        let resWzxlData = JSON.parse(res.data)[0].extendObjects;
        if (res.status == "success") {
          execServer("getAutoType", { phid: resWzxlData.phid_resbs }, function (res) {
            const datas = JSON.parse(res.data)[0].extendObjects;
            data[0].set("user_item_xl_name", datas.name);
            data[0].set("user_item_xl", resWzxlData.phid_resbs);
            data[0].set("user_item_zl_name", datas.fname);
            data[0].set("user_item_zl", datas.f_phid);
            data[0].set("user_item_dl_name", datas.gname);
            data[0].set("user_item_dl", datas.g_phid);
          });
        } else {
          Ext.Msg.alert("未查询到该物资类型");
        }
      });
    });
  function recommendWl(params) {
    let recommendSj = mstform.getItem("user_sjbm").getValue();
    if (recommendSj) {
      execServer("getYztjWl", { sjh: `'${recommendSj}'` }, function (res) {
        if (res.count == 0) return;
        const datas = JSON.parse(res.data);
        const itemDataArray = datas.map((item) => item?.extendObjects?.item_data);
        const validItemData = itemDataArray.filter((item) => item !== undefined && item !== null);
        Ext.each(dstore.getRange(), function (records, index) {
          const row = records.store.data.items;
          Ext.each(row, function (r) {
            const current = r.data.PhidItemdata;
            console.log(r.data.user_sfyztj);
            // 判断是否存在并设置user_sfyztj字段
            r.set("user_sfyztj", validItemData.includes(current) ? "1" : "0");
            if (r.data.user_sfyztj == 1) {
              let ssenum = r.data.user_review_prc - r.data.user_djdj;
              let sslnum = (r.data.user_review_prc - r.data.user_djdj) / r.data.user_djdj;
              r.set("user_sse", ssenum);
              r.set("user_ssl", sslnum);
            }
          });
        });
      });
    } else {
      console.log("未查询到该物资类型");
    }
  }
  let reqs = [];
  if (otype !== "view") {
    dstore.on("datachanged", async function (dstore, eOpts) {
      let PhidSenComp = mstform.getItem("PhidSenComp").getValue();
      let user_sjbm = mstform.getItem("user_sjbm").getValue();
      tarChange();
      recommendWl();
      dstore.each(function (record) {
        record.set("user_yhsyl", record.get("Qty"));
        let jbr = (record.get("user_pshsdj") - record.get("PrcFc")) * record.get("Qty");
        record.set("user_jcb_amt", jbr);
        console.log(record.data);
        let phid1 = record.data.PhidItemdata;
        if (record.data.PhidItemdata) {
          execServer("getDHZQItemDataInfo", { phid: `'${phid1}'` }, function (res) {
            try {
              const datas = JSON.parse(res.data);
              let DHZQ1 = datas[0].extendObjects.user_dhzq;
              const newDate = addDaysToDate(mstform.getItem("BillDt").value, DHZQ1);
              record.set("user_ckdh_dt", newDate);
            } catch (error) {
              Ext.Msg.alert("服务器错误，请联系管理员");
            }
          });
        } else if (record.data.PhidItemId) {
          execServer("getDHZQItemDataInfo", { phid: record.data.PhidItemId }, function (res) {
            try {
              const datas = JSON.parse(res.data);
              let DHZQ1 = datas[0].extendObjects.user_dhzq;
              const newDate = addDaysToDate(mstform.getItem("BillDt").value, DHZQ1);
              record.set("user_ckdh_dt", newDate);
            } catch (error) {
              Ext.Msg.alert("服务器错误，请联系管理员");
            }
          });
        }
        var taxRates = [];
        const currentTaxRate = record.data.TaxRate; // 获取当前行的税率
        taxRates.push(currentTaxRate); // 存入数组
        const isAllSame = taxRates.length > 0 && taxRates.every((rate) => rate === taxRates[0]);
        if (isAllSame) {
          allSameValue = taxRates[0]; // 保存相同的税率值
          mstform.getItem("user_taxrate").setValue(allSameValue);
          console.log("统一税率值:", allSameValue);
          // 在此执行你的统一逻辑（例如更新全局变量或界面）
        } else {
          mstform.getItem("user_taxrate").setValue("");
          console.log("税率不一致");
          // 在此执行不一致逻辑
        }
        async function asfun() {
          try {
            const res1 = await new Promise((resolve, reject) => {
              execServer("autoSelectType", { id: record.data.PhidItemId }, function (res) {
                resolve(res);
              });
            });
            console.log(res1);

            if (res1.count != 0) {
              const resWzxlData = JSON.parse(res1.data)[0].extendObjects;
              console.log(resWzxlData);

              const res2 = await new Promise((resolve, reject) => {
                execServer("getAutoType", { phid: resWzxlData.phid_resbs }, function (res) {
                  resolve(res);
                });
              });
              const datas = JSON.parse(res2.data)[0].extendObjects;

              record.set("user_item_xl_name", datas.name);
              record.set("user_item_xl", resWzxlData.phid_resbs);
              record.set("user_item_zl_name", datas.fname);
              record.set("user_item_zl", datas.f_phid);
              record.set("user_item_dl_name", datas.gname);
              record.set("user_item_dl", datas.g_phid);
            }
          } catch (error) {
            console.error(error);
          }
        }

        if (!record.data.PhidItemId) return;
        record.set("ItemName", record.data.PhidItemId_EXName);
        record.set("ItemNo", record.data.ItemDataNo);
        if (PhidSenComp && user_sjbm && record.data.PhidItemId) {
          getBeforePrice(record);
        }

        asfun();
      });
      SetTotal();
    });
  }

  function getBeforePrice(record) {
    let PhidSenComp = mstform.getItem("PhidSenComp").getValue();
    let user_sjbm = mstform.getItem("user_sjbm").getValue();
    execServer("getBeforePrice", { comphid: PhidSenComp, sjbm: `'${user_sjbm}'`, itemphid: record.data.PhidItemId }, function (res) {
      if (!(res?.count > 0)) return;
      try {
        const parsedData = JSON.parse(res.data || "[]")[0]?.extendObjects;
        if (!parsedData) return;

        record.set("PrcVatFc", parsedData.hsprc ?? record.get("PrcVatFc"));
        record.set("TaxRate", parsedData.taxrate ?? record.get("TaxRate"));
        record.set("PrcFc", parsedData.wsprc ?? record.get("PrcFc"));
      } catch (error) {
        console.log("getBeforePrice 解析错误", error);
      }
    });
  }

  function SetTotal() {
    var total = 0; //金额
    // 遍历 dstore 中的每个项
    dstore.each(function (item) {
      // 转换为数字

      let PlanPrc = Ext.Number.from(item.get("user_review_prc"), 0);
      let PrcFc = Ext.Number.from(item.get("PrcFc"), 0);
      let Qty = Ext.Number.from(item.get("Qty"), 0);
      console.log(PlanPrc, PrcFc, Qty);

      if (!PlanPrc || !PrcFc || !Qty) return;
      total += (PlanPrc - PrcFc) * Qty;
    });
    console.log(total);

    mstform.getItem("user_jcb_amt").setValue(total);
  }
  function addContractTerms(params) {
    tabPanel.setActiveTab(2);
    var dgrid3 = Ext.getCmp("cntitemtab").items.items[0].items.items[0];
    if (dgrid3) {
      // var GridID = Ext.getElementById(Ext.getElementById(Ext.getElementById(Ext.getElementById(Ext.getElementById(Ext.getElementById("cntitemtab-innerCt").children[0].id).children[0].id).children[0].id).children[0].id).children[2].id).children[0].id;
      // var grid1 = Ext.getCmp(GridID);
      let datas = [];
      datas.push(
        {
          NameNew: "预付款",
          PayType: "0",
          Remarks: "",
          PayProptyNew: "2",
          PayBaseTypeNew: "1",
          PhidItem: 8570000000000001,
          PhidItemNew: 8570000000000001,
        },
        // {
        // 	NameNew: "结算付款",
        // 	PayType: "1",
        // 	Remarks: "111",
        // 	PayProptyNew: "2",
        // 	PayBaseTypeNew: "1",
        // },
        // {
        // 	NameNew: "进度款",
        // 	PayType: "1",
        // 	Remarks: "111",
        // 	PayProptyNew: "2",
        // 	PayBaseTypeNew: "1",
        // },
        {
          NameNew: "设备到货",
          PayType: "1",
          Remarks: "",
          PayProptyNew: "2",
          PayBaseTypeNew: "1",
          PhidItem: 8570000000000008,
          PhidItemNew: 8570000000000008,
        },
        {
          NameNew: "安装调试款",
          PayType: "1",
          Remarks: "",
          PayProptyNew: "2",
          PayBaseTypeNew: "1",
          PhidItem: 8570000000000005,
          PhidItemNew: 8570000000000005,
        },
        {
          NameNew: "验收款",
          PayType: "1",
          Remarks: "",
          PayProptyNew: "2",
          PayBaseTypeNew: "1",
          PhidItem: 8570000000000004,
          PhidItemNew: 8570000000000004,
        },
        {
          NameNew: "审计款",
          PayType: "1",
          Remarks: "",
          PayProptyNew: "2",
          PayBaseTypeNew: "1",
        },
        {
          NameNew: "质保金",
          PayType: "1",
          Remarks: "",
          PayProptyNew: "2",
          PayBaseTypeNew: "1",
          PhidItem: 8570000000000007,
          PhidItemNew: 8570000000000007,
        }

        // {
        // 	NameNew: "安装完成",
        // 	PayType: "1",
        // 	Remarks: "111",
        // 	PayProptyNew: "2",
        // 	PayBaseTypeNew: "1",
        // },
        // {
        // 	NameNew: "调试完成",
        // 	PayType: "1",
        // 	Remarks: "111",
        // 	PayProptyNew: "2",
        // 	PayBaseTypeNew: "1",
        // }
      );
      dgrid3.store.add(datas);
    }
    tabPanel.setActiveTab(0);
  }

  //计算结算信息中的逻辑

  //到货周期时间计算
  function addDaysToDate(dateStr, days) {
    // 将日期字符串转换为 Date 对象
    const date = new Date(dateStr);
    // 在当前日期的基础上加上指定的天数
    date.setDate(date.getDate() + parseInt(days));

    // 获取新日期的年、月、日
    const year = date.getFullYear();
    // 月份需要加 1，因为 getMonth 返回值是 0 - 11
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");

    // 按照 YYYY.MM.DD 格式返回新日期
    return `${year}-${month}-${day}`;
  }
}
function beforeSaveEdit() {
  // 1. 获取稳定的父容器（根据ID）
  const parentTab = document.getElementById("cntitemtab");
  if (!parentTab) {
    // alert("错误：主容器未找到");
    // return false;
  }

  // 2. 逐层定位目标网格（假设结构为 div → div → span → div → 目标网格）
  const targetGrid = parentTab
    .querySelector("#cntitemtab-body") // 第一层子容器
    ?.querySelector("div > div > span > div") // 层级路径
    ?.querySelector("div.x-grid:first-child"); // 目标网格（假设类名包含 x-grid）

  // 3. 验证是否找到有效网格
  if (!targetGrid) {
    // alert("错误：支付比例网格未找到");
    // return false;
  }

  // 4. 获取 ExtJS 组件实例（通过 Ext.getCmp 或 DOM 关联）
  const extGrid = Ext.getCmp(targetGrid.id); // 依赖 ExtJS 的 DOM 关联
  if (!extGrid || !extGrid.store) {
    // alert("错误：网格数据未初始化");
    // return false;
  }

  // 5. 计算总和（处理浮点精度）
  let totalBfb = 0;
  if (!extGrid.store || extGrid.store.getCount() === 0) {
    return true; // 无数据直接放行
  }

  extGrid.store.each((item) => {
    console.log(item);

    const val = Ext.Number.from(item.get("BalPercent"), 0);
    totalBfb = +(totalBfb + val).toFixed(4); // 保留四位小数
  });

  // 6. 校验逻辑
  if (Math.abs(totalBfb - 1) > 0.001) {
    Ext.Msg.alert("提示", `合同支付比例总和为 ${(totalBfb * 100).toFixed(2)}%，请调整为100%`);
    return false;
  }

  return true;
}
